package public

import (
	"bytes"
	"encoding/json"
	"errors"
	"github.com/spf13/viper"
	"io/ioutil"
	"net/http"
)

type JsonPostSample struct {
	Code string `json:"code"`
	ErrorMsg string `json:"errorMsg"`
	Yzm string `json:"yzm"`
}

func  Sms(phone string,code int32) (int,error){
	params := make(map[string]interface{})
	viper.SetConfigName("base")
	viper.SetConfigType("toml")
	viper.AddConfigPath("./conf/dev/")
	err := viper.ReadInConfig()
	if err != nil {
		var errs error = errors.New("获取配置错误")
		return 0,errs
	}
	//请登录zz.253.com获取API账号、密码以及短信发送的URL
	params["account"] = viper.Get("sms253.account")  //创蓝API账号
	params["password"] = viper.Get("sms253.password") //创蓝API密码
	params["phone"] = phone //手机号

	//设置您要发送的内容：其中“【】”中括号为运营商签名符号，多签名内容前置添加提交
	params["msg"] ="【英皇钟表】验证码为："+String(code)+"，您正在尝试变更重要信息，请妥善保管账户信息。"
	params["report"] = "true"
	bytesData, err := json.Marshal(params)
	if err != nil {
		//fmt.Println(err.Error() )
		return 0,err
	}
	reader := bytes.NewReader(bytesData)
	url := "http://smssh1.253.com/msg/v1/send/json"  //短信发送URL
	request, err := http.NewRequest("POST", url, reader)
	if err != nil {
		//fmt.Println(err.Error())
		return 0,err
	}
	request.Header.Set("Content-Type", "application/json;charset=UTF-8")
	client := http.Client{}
	resp, err := client.Do(request)
	if err != nil {
		//fmt.Println(err.Error())
		return 0,err
	}
	respBytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return 0,err
	}

	//str := unsafe.Pointer(&respBytes)
	res := &JsonPostSample{}
	json.Unmarshal([]byte(respBytes), &res)

	//fmt.Println(res.Code)
	//fmt.Println(res.ErrorMsg)
	if res.Code!="0"{
		var errs error = errors.New("系统错误,"+res.ErrorMsg)
		return 0,errs
	}
	var errs error = errors.New(String(code))
	return 1,errs

}